import {
  Button,
  Form,
  Grid,
  Input,
  Message,
  Select,
  Typography,
  Upload,
} from "@arco-design/web-react";
import "./index.less";
import CustomStep from "@/components/CustomStep";
import { appTypeList, scoringStrategyList } from "@/enum/CommonEnum";
import { history, useLocation } from "umi";
import { addApp, editApp, updateApp } from "@/servers/api/appController";
import { ResponseCode } from "@/enum/ResponseCode";
import { useState, useRef, useEffect } from "react";
import { ScoringStrategy } from "@/enum/ScoringStrategy";
import { FILE_UPLOAD_URL } from "@/constant/common";
import { uploadFile } from "@/servers/api/fileController";
import request from "@/utils/request";
import { UploadBizEnum } from "@/enum/UploadBizEnum";
import { name } from "pubsub-js";
const { Title } = Typography;
const FormItem = Form.Item;
const Option = Select.Option;
export default () => {
  const [fileList, setFileList] = useState([]);
  const [appForm] = Form.useForm();
  const [flag, setFlag] = useState(false);
  const location = useLocation();
  //@ts-ignore
  let app = (location.state?.app as API.AppVO) || {};
  const [isAi, setIsAi] = useState<boolean>(
    app?.scoringStrategy === ScoringStrategy.AI
  );
  const onChange = (files: any) => {
    setFileList(files);
    setFlag(true);
  };
  const uploadIcon = async () => {
    const file = fileList[0];
    const formData = new FormData();
    //@ts-ignore
    formData.append("file", file.originFile);
    formData.append("biz", UploadBizEnum.APP_ICON);
    let res = await request.post(FILE_UPLOAD_URL, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
    if (res.data.code === ResponseCode.SUCCESS) {
      return res.data.data;
    } else {
      return "";
    }
  };
  const saveApp = async () => {
    if (flag) {
      let url = await uploadIcon();
      app.appIcon = url;
    }
    try {
      await appForm.validate();
      let appTemp = appForm.getFieldsValue();
      Object.assign(app, appTemp);
      let res = null;
      if (app?.id) {
        res = await editApp(app);
        if (res.data.code === ResponseCode.SUCCESS) {
          Message.success("修改应用成功");
          history.push("/add/question", {
            app,
          });
        } else {
          Message.error("修改应用失败");
        }
      } else {
        res = await addApp(app);
        if (res.data.code === ResponseCode.SUCCESS) {
          Message.success("创建应用成功");
          history.push("/add/question", {
            appId: res.data.data as any,
            app,
          });
        } else {
          Message.error("创建应用失败");
        }
      }
    } catch (e) {
      Message.error({
        content: "请完善信息",
        showIcon: true,
      });
    }
  };
  useEffect(() => {
    if (app?.id) {
      setFileList([
        //@ts-ignore
        {
          uid: "-1",
          name: app?.appName,
          url: app?.appIcon,
        },
      ]);
    }
  }, []);
  return (
    <div className="addAppPage">
      <Grid.Row align="start" justify="space-around">
        <Grid.Col xs={24} md={3}>
          <CustomStep
            isAi={isAi}
            prefix={!app?.id ? "创建" : "修改"}
            current={1}
          />
        </Grid.Col>
        <Grid.Col xs={24} md={19}>
          <Title heading={3}>{!app?.id ? "创建" : "修改"}应用</Title>
          <Form
            form={appForm}
            labelAlign="left"
            style={{ width: 450 }}
            autoComplete="off"
            initialValues={app}
            onChange={(val, all) => {
              setIsAi(all?.scoringStrategy === ScoringStrategy.AI);
            }}
          >
            <FormItem
              label="应用名称"
              field="appName"
              rules={[
                {
                  required: true,
                  message: "输入应用名称",
                  type: "string",
                },
              ]}
            >
              <Input placeholder="输入应用名称" />
            </FormItem>
            <FormItem
              label="应用描述"
              field="appDesc"
              rules={[
                {
                  required: true,
                  message: "输入应用描述",
                  type: "string",
                },
              ]}
            >
              <Input.TextArea placeholder="输入应用描述" />
            </FormItem>
            <FormItem
              label="应用图标"
              rules={[
                {
                  required: true,
                  message: "输入应用图标",
                  type: "string",
                },
              ]}
            >
              <Upload
                multiple
                imagePreview
                limit={1}
                autoUpload={false}
                fileList={fileList}
                onChange={onChange}
                //@ts-ignore
                action={FILE_UPLOAD_URL}
                listType="picture-card"
              />
            </FormItem>
            <FormItem
              label="应用类型"
              field="appType"
              rules={[
                {
                  required: true,
                  message: "选择应用类型",
                  type: "number",
                },
              ]}
            >
              <Select placeholder="选择应用类型" style={{ width: 154 }}>
                {appTypeList.map((item, index) => (
                  <Option key={index} value={item.value}>
                    {item.label}
                  </Option>
                ))}
              </Select>
            </FormItem>
            <FormItem
              label="评分策略"
              field="scoringStrategy"
              rules={[
                {
                  required: true,
                  message: "选择评分策略",
                  type: "number",
                },
              ]}
            >
              <Select placeholder="选择评分策略" style={{ width: 154 }}>
                {scoringStrategyList.map((item, index) => (
                  <Option key={index} value={item.value}>
                    {item.label}
                  </Option>
                ))}
              </Select>
            </FormItem>
          </Form>
          <Button onClick={saveApp} type="primary" style={{ width: "200px" }}>
            提交
          </Button>
        </Grid.Col>
      </Grid.Row>
    </div>
  );
};
